package repository

import (
	"gorm.io/gorm"
	"shop-bean/model"
	"shop-common/utils/queryWrapper"
)

type IAttachFileRepository interface {
	CheckAttachFileExist(*gorm.DB, *model.AttachFile) (int64, error)
	Create(*gorm.DB, *model.AttachFile) error
	FindExpireFile(*gorm.DB) ([]*model.AttachFile, error)
	DeleteBatch(*gorm.DB, []string) error
	UpdateBatchStatus(*gorm.DB, []uint, int) error
	FindOneByNameFile(*gorm.DB, *queryWrapper.WherePair) (*model.AttachFile, error)
}

type AttachFileRepository struct{}

func NewAttachFileRepository() IAttachFileRepository {
	return &AttachFileRepository{}
}

func (a *AttachFileRepository) Create(db *gorm.DB, file *model.AttachFile) error {
	return db.Create(&file).Error
}

// 3 正常, 2 过期, 1 用户上传附件24小时内都没使用该附件，该附件变为过期
func (a *AttachFileRepository) FindExpireFile(db *gorm.DB) (files []*model.AttachFile, err error) {
	return files, db.Model(&model.AttachFile{}).
		Where("status = 1").
		Where("UNIX_TIMESTAMP( expire_at ) < UNIX_TIMESTAMP( NOW() )").
		Or("status = 2").
		Find(&files).Error
}

func (a *AttachFileRepository) CheckAttachFileExist(db *gorm.DB, file *model.AttachFile) (count int64, err error) {
	return count, db.Model(&model.AttachFile{}).Where(" file_name = ? ", file.FileName).Count(&count).Error
}

func (a *AttachFileRepository) DeleteBatch(db *gorm.DB, fileNames []string) error {
	return db.Where("file_name IN ?", fileNames).Delete(&model.AttachFile{}).Error
}

func (a *AttachFileRepository) UpdateBatchStatus(db *gorm.DB, files []uint, state int) error {
	for _, file := range files {
		err := db.Model(&model.AttachFile{}).Where(" file_id = ? ", file).Update("status", state).Error
		if err != nil {
			return err
		}
	}
	return nil
}

func (a *AttachFileRepository) FindOneByNameFile(db *gorm.DB, wp *queryWrapper.WherePair) (info *model.AttachFile, err error) {
	return info, db.Model(&model.AttachFile{}).Where(wp.Query, wp.Args...).First(&info).Error
}
